package it.aekidna.cleverplatypus.mediator.tools
{
	import it.aekidna.cleverplatypus.mediator.MediationInfo;
	import it.aekidna.cleverplatypus.mediator.MediationRegistry;
	
	import mx.collections.ArrayCollection;
	
	public class MediationRegistryToolDM
	{
		[Bindable]
		public var mediatorsInfo : ArrayCollection = new ArrayCollection();

		public function MediationRegistryToolDM()
		{
		}

			public function init() : void
			{
				for each( var eventName : String in MediationRegistry.getInstance().events )
				{
					var names : Object = {};
					  
					for each( var info : MediationInfo in MediationRegistry.getInstance().getMethodsByEventName( eventName ) )
					{
						if( !names.hasOwnProperty( info.eventName ) )
						{
							names[ info.eventName ] = new MediationRegistryToolMediationDescriptor( info ); 
							mediatorsInfo.addItem( names[ info.eventName ] );
						}
						MediationRegistryToolMediationDescriptor( names[ info.eventName ] ).listeners.addItem( info.listenerObjectClass );						
					}
				}
				mediatorsInfo.refresh();
				MediationRegistry.getInstance().registerMediator(
					MediationRegistry.MEDIATOR_REGISTERED,
					[ "info" ],
					onMediationRegistered,
					this );
				MediationRegistry.getInstance().registerMediator(
					MediationRegistry.PERFORMING_MEDIATION,
					[ "info", "params" ],
					onMediationPerformed,
					this );
			}

			private function onMediationRegistered( inInfo : MediationInfo ) : void
			{
				var descriptor : MediationRegistryToolMediationDescriptor;
				for each( descriptor in mediatorsInfo )
				{
					if( descriptor.info.eventName == inInfo.eventName )
					{
						break;
					} 
					else
					{
						descriptor = null;
					}
				}
				if( descriptor == null )
				{
					descriptor = new MediationRegistryToolMediationDescriptor( inInfo );
				}
				else
				{
					descriptor.listeners.addItem( inInfo.listenerObjectClass );
				}
				mediatorsInfo.addItem( descriptor );
				mediatorsInfo.refresh();
			}
			
			private function onMediationPerformed( inInfo : MediationInfo, inParams : Array ) : void
			{
				var descriptor : MediationRegistryToolMediationDescriptor;
				for each( descriptor in mediatorsInfo )
				{
					if( descriptor.eventName == inInfo.eventName )
					{
						break;
					}
					else
					{
						descriptor = null;
					}
				}
				if( descriptor != null )
				{
					descriptor.onCall( inParams );
					mediatorsInfo.refresh();
				}
			}


	}
}